package com.shareppy.norman.sqlite.db;

import java.util.List;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Pair;

import com.shareppy.norman.core.entity.AbstractEntity;
import com.shareppy.norman.core.procedures.InitialData;
import com.shareppy.norman.core.schema.SchemaGenerator;
import com.shareppy.norman.sqlite.schema.SQLiteSchemaGenerator;

public class SQLiteDBHelper extends SQLiteOpenHelper{
	
	private Class<? extends AbstractEntity>[] entities;
	private InitialData initialScript;

	public SQLiteDBHelper(Context context, String name, int version,
			InitialData initialScript, Class<? extends AbstractEntity>... entities) {
		super(context, name, null, version);
		this.entities = entities;
		this.initialScript = initialScript;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		List<Pair<String, String>> attachedDbs = db.getAttachedDbs();
		for (Pair<String, String> pair : attachedDbs) {
			System.out.println(pair.first + "...." + pair.second);
		}
		if (entities != null) {
			SchemaGenerator asg = new SQLiteSchemaGenerator();
			try {
				for (Class<? extends AbstractEntity> entity : entities) {
					db.execSQL(asg.ddl(entity));
				}
				if (initialScript != null) {
					initialScript.run(new SQLiteConnection(db));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

}
